//
// Created by Administrator on 2023/11/15.
//
#include "iostream"
#include "queue"

using namespace std;

const int N = 110;
int g[N][N], d[N][N];

int m, n;

typedef pair<int, int> PII;

queue<PII> q;

void bfs() {
    q.push({0, 0});
    d[0][0] = 0;

    // 四个方向
    int dx[4]{-1, 0, 1, 0};
    int dy[4] = {0, 1, 0, -1};

    while (!q.empty()) {
        //取队头
        PII t = q.front();
        q.pop();
        // 看对头的四个方向
        for (int i = 0; i < 4; ++i) {
            int x = t.first + dx[i];
            int y = t.second + dy[i];
            //在图中，且可行，且没有被走过
            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
                //入队
                q.push({x, y});
                // 距离原点距离+1
                d[x][y] = d[t.first][t.second] + 1;
            }
        }
    }
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
            d[i][j] = -1;
        }
    }
    bfs();
    cout << d[n - 1][m - 1];
}